package com.on.smile.impl;

import com.on.smile.dao.UserDao;
import com.on.smile.entity.UserEntity;
import com.on.smile.service.UserService;
import com.on.smile.util.MD5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserImpl implements UserService {
    @Resource
    private UserDao userDao;


    @Override
    public String register(UserEntity user) {
        // 先查一下是否存在
        UserEntity userEntity = userDao.selectByUserName(user.getUsername());

        // 这里应该直接判断userEntity
        // 因为如果没查到用户，userEntity是为null的

        if (userEntity != null) {
            return "已存在该用户，无法注册！";
        }

        String password = user.getPassword();
        String encrypt = MD5Utils.encrypt(password);
        user.setPassword(encrypt);
        userDao.insertUser(user);

        return "注册成功";
    }

    @Override
    public String login(String username, String password) {
        // 记住：判断最好只写if，不要用if  else  if
        // 通常先判断否定情况，先判断错的
        UserEntity userEntity = userDao.selectByUserName(username);
        if (userEntity == null) {
            return "账号不存在";
        }
        String encrypt1 = MD5Utils.encrypt(password);
        String password1 = userEntity.getPassword();
        if (!encrypt1.equals(password1)) {
            return "密码错误";
        }

        return "登陆成功";
    }

    @Override
    public String updatePassword(UserEntity userEntity) {
        String name= String.valueOf(userDao.selectByUserName(userEntity.getUsername()));
        if (name == null) {
            return "未查到该用户";
        }
        else {
            Long id = userEntity.getId();
            String newpassword = userEntity.getPassword();
            String encrypt = MD5Utils.encrypt(newpassword);
            int result = userDao.updatePassword(id, encrypt);
            if (result > 0) {
                return "修改密码成功";
            } else
                return "运行失败";
        }
    }
    @Override
    public String deleteById(UserEntity userEntity){
        String name= String.valueOf(userDao.selectByUserName(userEntity.getUsername()));
        if (name == null) {
            return "未查到该用户";
        }
        else {
            Long id=userEntity.getId();
            int result=userDao.deleteById(id);
            if(result>0)
            {
                return "删除成功";
            }
            else
                return "运行失败";
        }
    }
    @Override
    public List<UserEntity> selectByPage(Long page,Long size){
return userDao.selectByPage((page-1)*size,size);
    }
}
